package org.arain.baseii.system.resources;

import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.StringUtils;
import org.arain.baseii.aspect.annotation.SystemExceptionLog;
import org.arain.baseii.aspect.annotation.SystemServiceLog;
import org.arain.baseii.mapper.SysResourceMapper;
import org.arain.baseii.mapper.SysRoleResourceMapper;
import org.arain.baseii.pojo.SysResource;
import org.arain.baseii.pojo.SysResourceExample;
import org.arain.baseii.pojo.SysRoleResource;
import org.arain.baseii.pojo.SysUser;
import org.arain.baseii.utils.AppUtils;
import org.arain.baseii.utils.ArainResult;
import org.arain.baseii.utils.CommonContains;
import org.arain.baseii.utils.IDUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

/**
 * 
* <p>Title:SysResourcesServiceImpl </p>
* @author Arain
* @date2017年8月29日
 */
@Service
public class SysResourcesServiceImpl implements SysResourcesService{
	@Autowired
	private SysResourceMapper sysResourceMapper;
	@Value("${ADMIN}")
	private Long admin;
	@Autowired 
	private SysRoleResourceMapper sysRoleResourceMapper;
	@SuppressWarnings("rawtypes")
	@Override
	public List load_user_resources(HttpServletRequest request) {
		Long userId = AppUtils.getUserId();
		List<SysResource> list = sysResourceMapper.selectByUserId_sql((long) 0,userId);
		return list;
	}
	
	@Override
	public String load_user_children_resources(HttpServletRequest request, Long pid) {
		JSONArray array = new JSONArray();
		Long userId = AppUtils.getUserId();
		List<SysResource> list = sysResourceMapper.selectByUserId_sql(pid,userId);
		for (SysResource sysResource : list) {
			JSONObject object = new JSONObject();
			object.put("text", sysResource.getName());
			object.put("id", sysResource.getId());
			object.put("url", sysResource.getTarget());
			object.put("iconCls", sysResource.getIcon());
			object.put("pid",pid);
			array.add(object);
		}
		return array.toString();
	}

	@Override
	public String load_resources_treegrid(HttpServletRequest request) {
		JSONArray array = new JSONArray();
		SysResourceExample example = new SysResourceExample();
		example.createCriteria().andPidEqualTo((long) 0);
		List<SysResource> list = sysResourceMapper.selectByExample(example);
		int countByExample = sysResourceMapper.countByExample(example);
		for (SysResource sysResource : list) {
			JSONArray child = new JSONArray();
			JSONObject object = new JSONObject();
			object.put("id",sysResource.getId());
			object.put("name",sysResource.getName());
			object.put("type","菜单");
			object.put("sort",sysResource.getSort());
			object.put("target",sysResource.getTarget());
			object.put("icon","<span class=\""+sysResource.getIcon()+"\" style=\"display:inline-block;width:16px;margin-top:4px\">&nbsp;</span><span class=\"l-btn-text\">icon</span>");
			object.put("enabled", sysResource.getEnabled());
			
			SysResourceExample childexample = new SysResourceExample();
			childexample.createCriteria().andPidEqualTo(sysResource.getId());
			List<SysResource> childlist = sysResourceMapper.selectByExample(childexample);
			for (SysResource sysResourceChild : childlist) {
				JSONObject objectChild = new JSONObject();
				objectChild.put("id",sysResourceChild.getId());
				objectChild.put("name",sysResourceChild.getName());
				objectChild.put("type","模块");
				objectChild.put("sort",sysResourceChild.getSort());
				objectChild.put("target",sysResourceChild.getTarget());
				objectChild.put("icon","<span class=\""+sysResourceChild.getIcon()+"\" style=\"display:inline-block;width:16px;margin-top:4px\">&nbsp;</span><span class=\"l-btn-text\">icon</span>");
				objectChild.put("enabled", sysResourceChild.getEnabled());
				
				child.add(objectChild);
			}
			object.put("children",child);
			array.add(object);
		}
		
		JSONObject result = new JSONObject();
		result.put("total",countByExample);
		result.put("rows", array);
		return result.toString();
	}

	@Override
	@Cacheable(cacheNames="shirocache")
	public List<SysResource> load_all_resources(SysUser user) {
		List<SysResource> list = sysResourceMapper.selectAllChildByUserId_sql(user.getId());
		return list;
	}

	@Override
	public List<SysResource> load_all() {
		SysResourceExample example = new SysResourceExample();
		example.createCriteria().andEnabledEqualTo((short) 1);
		List<SysResource> list = sysResourceMapper.selectByExample(example);
		return list;
	}

	@Override
	public SysResourcesDto load_01(SysResourcesDto dto) {
		SysResource resource = sysResourceMapper.selectByPrimaryKey(Long.valueOf(dto.getId()));
		AppUtils.copyProperties(dto, resource);
		return dto;
	}

	@Override
	public String load_tree(HttpServletRequest request) {
		JSONArray array = new JSONArray();
		List<SysResource> list = sysResourceMapper.selectByUserId_sql((long) 0, AppUtils.getUserId());
		for (SysResource sysResource : list) {
			JSONObject object = new JSONObject();
			object.put("id", sysResource.getId());
			object.put("text", sysResource.getName());
			object.put("state","closed");
			
			JSONArray childArray = new JSONArray();
			List<SysResource> childList = sysResourceMapper.selectByUserId_sql(sysResource.getId(), AppUtils.getUserId());
			for (SysResource sysResourceChild : childList) {
				JSONObject objectChild = new JSONObject();
				objectChild.put("id", sysResourceChild.getId());
				objectChild.put("text", sysResourceChild.getName());
				objectChild.put("state","open");
				
				childArray.add(objectChild);
			}
			if(childArray.size() > 0) {
				object.put("state","closed");
			} else {
				object.put("state","open");
			}
			object.put("children", childArray);
			array.add(object);
		}
		return array.toString();
	}

	@SuppressWarnings("unchecked")
	@CacheEvict(value="shirocache",allEntries=true,beforeInvocation=true)
	@Override
	@SystemExceptionLog(description="保存")
	@SystemServiceLog(description="保存")
	public ArainResult save_01(SysResourcesDto dto) {
		net.sf.json.JSONArray resourceJsons=net.sf.json.JSONArray.fromObject(dto.getResourcesJson());
		if(StringUtils.isBlank(dto.getPid())) {
			dto.setPid("0");
		}
		if(StringUtils.isNotBlank(dto.getId())) {
			SysResource resource = sysResourceMapper.selectByPrimaryKey(Long.valueOf(dto.getId()));
			AppUtils.copyProperties(resource, dto);
			resource.setHavemune(CommonContains.getHaveMenu_yes());
			sysResourceMapper.updateByPrimaryKey(resource);
			
			SysRoleResource record = new SysRoleResource();
			record.setRoleId(admin);
			record.setChecked((short) 1);
			record.setResourceId(resource.getId());
			
//			sysRoleResourceMapper.insert(record);
			
			SysResourceExample example = new SysResourceExample();
			example.createCriteria().andPidEqualTo(resource.getId()).andHavemuneEqualTo((short) 0);
			sysResourceMapper.deleteByExample(example);
			
			List<SysResource> sysResourceDtos=(List<SysResource>) net.sf.json.JSONArray.toCollection(resourceJsons, SysResource.class);
			for (SysResource sysResource : sysResourceDtos) {
				sysResource.setEnabled(resource.getEnabled());
				sysResource.setPid(resource.getId());
				sysResource.setId(Long.valueOf(IDUtil.genId()));
				sysResource.setHavemune(CommonContains.getHaveMenu_no());
				sysResourceMapper.insert(sysResource);
				
				SysRoleResource record_child = new SysRoleResource();
				record_child.setRoleId(admin);
				record_child.setChecked((short) 1);
				record_child.setResourceId(sysResource.getId());
				sysRoleResourceMapper.insert(record_child);
				
			}
			return ArainResult.ok();
			
		} else {
			dto.setId(IDUtil.genId());
			SysResource resource = new SysResource();
			AppUtils.copyProperties(resource, dto);
			resource.setHavemune(CommonContains.getHaveMenu_yes());
			sysResourceMapper.insert(resource);
			SysRoleResource record = new SysRoleResource();
			record.setRoleId(admin);
			record.setChecked((short) 1);
			record.setResourceId(resource.getId());
			
			sysRoleResourceMapper.insert(record);
			List<SysResource> sysResourceDtos=(List<SysResource>) net.sf.json.JSONArray.toCollection(resourceJsons, SysResource.class);
			for (SysResource sysResource : sysResourceDtos) {
				sysResource.setEnabled(resource.getEnabled());
				sysResource.setPid(resource.getId());
				sysResource.setId(Long.valueOf(IDUtil.genId()));
				sysResource.setHavemune(CommonContains.getHaveMenu_no());
				sysResourceMapper.insert(sysResource);
				
				SysRoleResource record_child = new SysRoleResource();
				record_child.setRoleId(admin);
				record_child.setChecked((short) 1);
				record_child.setResourceId(sysResource.getId());
				sysRoleResourceMapper.insert(record);
			}
			return ArainResult.ok();
		}
	}

	@Override
	public String load_children_resources(SysResourcesDto dto) {
		if(StringUtils.isNotBlank(dto.getPid()) && !"null".equals(dto.getPid())) {
			JSONArray array = new JSONArray();
			SysResourceExample example = new SysResourceExample();
			example.createCriteria().andPidEqualTo(Long.valueOf(dto.getPid())).andHavemuneEqualTo((short) 0);
			List<SysResource> list = sysResourceMapper.selectByExample(example);	
			for (SysResource sysResource : list) {
				JSONObject object = new JSONObject();
				object.put("name", sysResource.getName());
				object.put("enabled", sysResource.getEnabled());
				object.put("target", sysResource.getTarget());
				object.put("authorization", sysResource.getAuthorization());
				object.put("title", sysResource.getTitle());
				object.put("type", sysResource.getType());
				array.add(object);
			}
			return array.toString();
		}
		return "";
	}
}
